<?php
namespace Common\Model;

/**
 * ServerModel
 * 被监控服务器模型
 */
class ServerModel extends Model {
    protected $tableName = 'server';

    public function save2($d) {
        $id      = empty($d['id'])       ? null : (int)$d['id'];
        $name    = empty($d['name'])     ? null : trim($d['name']);
        $ip      = empty($d['ip'])       ? null : trim($d['ip']);
        $baseUrl = empty($d['base_url']) ? null : trim($d['base_url']);
        $comment = empty($d['comment'])  ? null : $d['comment'];
        $status  = !isset($d['status'])  ? 0    : (int)$d['status'];
        $dao     = array();

        if(empty($name)) {
            throw new Exception('请指定服务器名称');  
        }

        if(empty($id)) {
            $action = 'add';
            $checkExistNameExpr = array('name' => $name);
        } else {
            $action    = 'save';
            $dao['id'] = $id;
            $checkExistNameExpr = array('name' => $name, 'id' => array('NEQ', $id));
        }

        if($this->where($checkExistNameExpr)->find()) {
            throw new Exception('服务器名称已经存在');
        }

        if(empty($ip)) {
            throw new Exception('请指定IP地址');
        }

        if(empty($baseUrl)) {
            throw new Exception('请指定获取数据基准地址');  
        }

        $dao['name']     = $name;
        $dao['status']   = $status;
        $dao['ip']       = $ip;
        $dao['base_url'] = getFullUrl($baseUrl);
        $dao['comment']  = $comment;

        return $this->$action($dao);
    }

    public function del($id) {
        $id = (int)$id;

        if(empty($id)) {
            throw new Exception('参数不完整');  
        }

        $expr = array('id' => $id);

        return $this->where($expr)->delete();
    }

}
